<script setup lang="ts">
import dayjs from 'dayjs'

const props = withDefaults(defineProps<Props>(), {
  from: undefined,
  to: undefined,
  time: true,
})

const emit = defineEmits(['update:from', 'update:to'])

interface Props {
  from?: string
  to?: string
  time?: boolean
}

const attrs = useAttrs()

const range = ref()

const today = dayjs()
const shortcuts = [
{
    label: '今天',
    value: () => [today, today],
  },
  {
    label: '近7天',
    value: () => [today, today.add(-1, 'week')],
  },
  {
    label: '近30天',
    value: () => [today, today.add(-1, 'month')],
  },
  {
    label: '本月',
    value: () => [today.startOf('month'), today.endOf('month')],
  },
  {
    label: '上月',
    value: () => [today.subtract(1, 'month').startOf('month'), today.subtract(1, 'month').endOf('month')],
  },
]

watchEffect(() => {
  range.value = [props.from, props.to]
})

const onChange = (dateString, date) => {
  if (dateString && date) {
    emit('update:from', dateString[0])
    emit('update:to', dateString[1])
  } else {
    emit('update:from', '')
    emit('update:to', '')
  }
}
</script>

<template>
  <a-range-picker
    v-model="range"
    v-bind="attrs"
    :time-picker-props="time ? { defaultValue: ['00:00:00', '23:59:59'] } : undefined"
    :show-time="time"
    allow-clear
    :day-start-of-week="1"
    :shortcuts="time ? undefined : shortcuts"
    @change="onChange"
  />
</template>

<style scoped>

</style>
